<template>
	<view class="container">
		<view class="title">汽车保养</view>
		<view>
			<image class="back" src="/static/images/白色左箭头.png" mode="" @click="goBack"></image>
		</view>

		<!-- 附近加油 -->
		<view>
			<uni-card title="附近加油站" sub-title="根据您的位置推荐最近的加油站" extra="更多" :thumbnail="avatar">
				<map scale="16" :longitude="longitude" :latitude="latitude" class="map" :markers="markers"
					@markertap="mkp"></map>
				<view class="card" v-if="info.title != ''">
					<view class="merchant">
						<view class="merchant-name">{{ info.title }}</view>
						<view class="merchant-rating">{{ info.rating }}</view>
						<view class="merchant-info">{{ info.info }}</view>
						<view class="merchant-info">{{ info.location }}</view>
					</view>
					<view class="picture">
						<view style="margin-left: 50px; margin-top: 20px;">{{ distanceFromHere }} 米</view>
						<image src="/static/home/baoyang/screenshot2.png" mode=""></image>
					</view>
				</view>
				<view class="operate" v-if="info.title != ''">
					<button style="background-color: #3789ff;" @click="openPopup">
						<uni-icons type="phone" style="color: white;"></uni-icons>
						联系门店
					</button>
					<button style="background-color: #ff7438;" @click="nearbystores">
						<uni-icons type="calendar" style="color: white;"></uni-icons>
						立即预定
					</button>
				</view>
			</uni-card>
		</view>

		<uni-popup ref="popupRef" type="bottom" background-color="#fff" :border-radius="'10px 10px 0 0'">
			<view style="text-align: center;">
				<view style="padding: 30rpx 0; border-bottom: 0.5px solid #f2f2f2;">18640589156</view>
				<view style="padding: 30rpx 0; border-bottom: 0.5px solid #f2f2f2;">复制</view>
			</view>
		</uni-popup>

	</view>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		onMounted,
		ref,
		computed
	} from 'vue';

	// 预定页面默认隐藏
	const popupRef = ref(null);
	const openPopup = () => {
		popupRef.value.open('bottom')
	}

	const longitude = ref(0)
	const latitude = ref(0)
	const info = ref({
		title: '',
		info: ''
	})

	// 增加一个变量来跟踪信息是否应该显示
	const showInfo = ref(false);
	
	function mkp(e) {
	  const clickedMarker = markers.value.find(obj => obj.id == e.detail.markerId);
	  
	  // 如果点击的是当前位置标记（id=0），不更新信息
	  if (clickedMarker.id === 0) {
	    showInfo.value = false;
	    info.value = { title: '', info: '' };
	    return;
	  }
	  
	  // 如果再次点击同一个标记点，则隐藏信息
	  if (info.value.title === clickedMarker.title && showInfo.value) {
	    showInfo.value = false;
	    info.value = { title: '', info: '' };
	    return;
	  }
	  
	  // 否则显示新的信息
	  info.value = clickedMarker;
	  showInfo.value = true;
	
	  // 计算距离
	  const lat1 = latitude.value;
	  const lon1 = longitude.value;
	  const lat2 = info.value.latitude;
	  const lon2 = info.value.longitude;
	  const distance = calculateDistanceInMeters(lat1, lon1, lat2, lon2);
	  distanceFromHere.value = distance.toFixed(2);
	}

	// 计算距离
	const distanceFromHere = ref(0)

	function calculateDistanceInMeters(lat1, lon1, lat2, lon2) {
		const R = 6371000; // 地球半径，单位：米 结果为：米
		//const R = 6371; // 地球半径，单位：公里 结果为：公里
		const dLat = degToRad(lat2 - lat1);
		const dLon = degToRad(lon2 - lon1);
		const a =
			Math.sin(dLat / 2) * Math.sin(dLat / 2) +
			Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
			Math.sin(dLon / 2) * Math.sin(dLon / 2);
		const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		return R * c; // 距离，单位：米
	}

	// 辅助函数：将角度转换为弧度
	function degToRad(deg) {
		return deg * (Math.PI / 180);
	}

	function getLocation() {
		uni.getLocation({
			type: 'wgs84', // 确保获取的是WGS84坐标系
			success(res) {
				console.log('坐标信息', res)
				longitude.value = res.longitude
				latitude.value = res.latitude

				// 更新标记点
				updateMarkers()
			},
			fail(err) {
				console.error('获取位置失败', err)
				uni.showToast({
					title: '无法获取位置信息',
					icon: 'none'
				})
			}
		})
	}

	function choose() {
		uni.chooseLocation({
			success(res) {
				console.log('点击获取到了实时位置', res)
			}
		})
	}

	function goBack() {
		uni.navigateBack();
	}

	function nearbystores() {
		uni.navigateTo({
			url: "/pages/index/baoyang/nearbystores/nearbystores"
		})
	}

	// 基础标记点数据（不包含当前位置）
	const baseMarkers = [{
			id: 999,
			latitude: 34.826128,
			longitude: 113.558902,
			width: 15,
			height: 15,
			iconPath: '/static/dw.png',
			title: '华蓝集团',
			rating: '⭐⭐⭐⭐⭐   5分',
			info: '营业时间：周一至周六  早上9:00-晚上22:00',
			location: '位置:山阳区人民路与解放路交叉口',
			phone: '18912345678',
			callout: { // 自定义一直显示的数据，自己的定位信息
				color: "#fff",
				bgColor: '#000',
				borderRadius: 10,
				padding: 10,
				display: "ALWAYS",
			}
		},
		{
			id: 1,
			latitude: 34.826622,
			longitude: 113.556722,
			width: 15,
			height: 15,
			iconPath: '/static/dw.png',
			title: '建华北京烤鸭',
			rating: '⭐⭐⭐⭐⭐   5分',
			info: '营业时间：周一至周日  早上8:00-晚上18:00',
			location: '位置:山阳区人民路与解放路交叉口',
			phone: '18912345678',
		},
		{
			id: 2,
			latitude: 34.824521,
			longitude: 113.557732,
			width: 15,
			height: 15,
			iconPath: '/static/dw.png',
			title: '郑州德析检测技术有限公司',
			rating: '⭐⭐⭐   3分',
			info: '营业时间：周一至周五  早上8:00-晚上22:00',
			location: '位置:山阳区人民路与解放路交叉口',
			phone: '18912345678',
		},
		{
			id: 3,
			latitude: 34.827359,
			longitude: 113.557851,
			iconPath: '/static/dw.png',
			width: 15,
			height: 15,
			title: '肿瘤医院',
			rating: '⭐⭐⭐⭐   4分',
			info: '营业时间：周一至周日  早上0:00-晚上24:00',
			location: '位置:山阳区人民路与解放路交叉口',
			phone: '18912345678',
		},
		{
			id: 4,
			latitude: 34.827537,
			longitude: 113.560137,
			iconPath: '/static/dw.png',
			width: 15,
			height: 15,
			title: '顺丰驿站',
			rating: '⭐⭐⭐⭐   4分',
			info: '营业时间：周一至周日  早上8:00-晚上20:30',
			location: '位置:山阳区人民路与解放路交叉口',
			phone: '18912345678',
		}
	]

	// 标记点数据
	const markers = ref([])

	// 更新标记点函数
	function updateMarkers() {
		// 创建当前位置标记
		const currentLocationMarker = {
			id: 0,
			latitude: latitude.value,
			longitude: longitude.value,
			iconPath: '/static/home/maps/mylocation.png',
			width: 15, // 增大图标尺寸以便更明显
			height: 15,
			callout: {
				content: "当前位置",
				color: "#fff",
				bgColor: '#000',
				borderRadius: 10,
				padding: 10,
				display: "ALWAYS",
			}
		}

		// 更新标记点数组（替换整个数组以触发更新）
		markers.value = [currentLocationMarker, ...baseMarkers]
	}

	onLoad(() => {
		// 初始时先设置默认标记点（不含当前位置）
		markers.value = [...baseMarkers]

		// 然后获取位置并更新标记点
		getLocation();
	})
</script>

<style>
	.container {
		width: 100%;
		height: 400rpx;
		background-image: url(/static/homebg.png);
		background-size: 100%;
	}

	.title {
		color: white;
		width: 100%;
		text-align: center;
		padding-top: 12px;
	}

	.back {
		position: absolute;
		left: 30rpx;
		top: 34rpx;
		width: 15px;
		height: 15px;
		z-index: 2;
	}

	.map {
		width: 100%;
		height: 700rpx;
	}

	.card {
		display: flex;
	}

	.merchant {
		width: 74%;
		font-size: 12px;
		color: black;
		margin: 15px 0;
	}

	.merchant-name {
		font-size: 16px;
		font-weight: 600;
		margin: 15px 0 5px 0;
	}

	.picture {
		color: #3385fd;
		font-size: 12px;
	}

	.picture image {
		width: 200rpx;
		height: 160rpx;
	}

	.operate {
		display: flex;
		justify-content: space-between;
	}

	.operate button {
		font-size: 14px;
		border-radius: 200px;
		width: 260rpx;
		color: white;
	}

	.contact {
		width: 100%;
		position: fixed;
		/* 固定定位 */
		bottom: 0;
		/* 底部对齐 */
		background-color: #fff;
		/* 背景色 */
		padding: 10px;
		/* 内边距 */
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
		/* 阴影 */
		border-radius: 20px;
	}

	.merchant-phone {
		padding: 8px 0;
		text-align: center;
		font-size: 18px;
		margin-bottom: 10px;
	}

	button {
		width: 100%;
		font-size: 14px;
		border-radius: 200px;
		background-color: #ffffff;
		color: black;
		border: #fff 1px solid;
	}
</style>